package com.haiertvbic.tvnow.util;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.haiertvbic.tvnow.model.ProgramDetail;
import com.haiertvbic.tvnow.network.NetUtil;

public class TimeUtil {
	/**
	 * 如果明天的周数返回true
	 * 
	 * @param program
	 * @return
	 */
	public static boolean isTomorrowWeek(ProgramDetail program) {
		int programWeek = program.getPweekday();
		if (programWeek == getWeek()) {
			return false;
		} else {
			return true;
		}
	}

	public static int getWeek() {
		Calendar c = Calendar.getInstance();
		// 得到当前是周几
		int week = c.getTime().getDay();
		if (week == 0) {
			week = 7;
		}
		return week;
	}

	/**
	 * 根据无网、时间判断是否删除表,每天都会更新
	 * 
	 * @return 返回true表示删表
	 */
	public static boolean isDeleteProgram(Context context) {
		boolean isDelete = false;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String currentDay = df.format(new Date());
		String yesterday;
		SharedPreferences fromSP = context.getSharedPreferences("yesterday",
				Context.MODE_PRIVATE);
		String yesterdayTemp = fromSP.getString("yesterday", "nodate");
		Editor toSP = context.getSharedPreferences("yesterday",
				Context.MODE_PRIVATE).edit();

		if (yesterdayTemp.equals("nodate")) {
			yesterday = currentDay;
			toSP.putString("yesterday", yesterday);
			toSP.commit();
			isDelete = true;
		} else {
			yesterday = yesterdayTemp;
			try {
				long currentDayLong = df.parse(currentDay).getTime();
				long yesterdayLong = df.parse(yesterday).getTime();
				if (currentDayLong != yesterdayLong
						&& NetUtil.getNetworkInfo(context)) {
					// 有网络删数据
					yesterday = currentDay;
					toSP.putString("yesterday", yesterday);
					toSP.commit();
					isDelete = true;
				}
			} catch (ParseException e) {
			}
		}
		return isDelete;
	}

	/**
	 * 一周更新一次
	 * 
	 * @return 返回真表示该更新了
	 */
	public static boolean isDeleteItem(Context context) {
		boolean isDelete = false;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String currentDay = df.format(new Date());
		String day;
		Editor toSP = context.getSharedPreferences("yesterday",
				Context.MODE_PRIVATE).edit();
		SharedPreferences fromSP = context.getSharedPreferences("yesterday",
				Context.MODE_PRIVATE);
		String dayTemp = fromSP.getString("day", "nodate");
		if (dayTemp.equals("nodate")) {
			day = currentDay;
			toSP.putString("day", day);
			toSP.commit();
			isDelete = false;
		} else {
			day = dayTemp;
			try {
				long seven = 604800000;// 表示一周
				long currentDayLong = df.parse(currentDay).getTime();
				long dayLong = df.parse(day).getTime() + seven;
				if (NetUtil.getNetworkInfo(context) && currentDayLong > dayLong) {
					day = currentDay;
					toSP.putString("day", day);
					toSP.commit();
					isDelete = true;
				}
			} catch (ParseException e) {
			}
		}

		return isDelete;
	}

	/**
	 * 得节目的长度，单位是分钟
	 * 
	 * @param pro
	 * @return
	 */
	public static int getProgramTimeLength(ProgramDetail pro) {
		int lastTime = 0;
		String startTime = pro.getPstime();
		String[] startArray = startTime.split(":");
		String startHHString = startArray[0];
		startHHString = startHHString.trim();
		int startHH = Integer.valueOf(startHHString);
		String startMinuteString = startArray[1];
		startMinuteString = startMinuteString.trim();
		int startMinute = startHH * 60 + Integer.valueOf(startMinuteString);

		String endTime = pro.getPftime();
		String[] endArray = endTime.split(":");

		String endHHString = endArray[0];
		endHHString = endHHString.trim();
		int endHH = Integer.valueOf(endHHString);
		String endMinuteString = endArray[1];
		endMinuteString = endMinuteString.trim();
		int endMinute = endHH * 60 + Integer.valueOf(endMinuteString);

		if (!isCriticalDay(startTime, endTime)) {
			lastTime = endMinute - startMinute;
		} else {
			String[] endArray1 = "23:59:59".split(":");
			int endHH1 = Integer.valueOf(endArray1[0]);
			int endMinute1 = endHH1 * 60 + Integer.valueOf(endArray1[1]);

			lastTime = endMinute1 - startMinute + endMinute;
		}
		return lastTime;
	}

	/**
	 * 节目播放了多久，单位是分钟
	 * 
	 * @param pro
	 * @param context
	 * @return
	 */
	public static int getProgramPassedTime(ProgramDetail pro, Context context) {
		int passedTime = 0;

		String startTime = pro.getPstime();
		String[] startArray = startTime.split(":");

		String startHHString = startArray[0];
		startHHString = startHHString.trim();
		int startHH = Integer.valueOf(startHHString);

		String startMinuteString = startArray[1];
		startMinuteString = startMinuteString.trim();
		int startMinute = startHH * 60 + Integer.valueOf(startMinuteString);

		if (!isCriticalDay(startTime, pro.getPftime())) {
			passedTime = getCurrentMinute("HH:mm:ss") - startMinute;
		} else {
			String[] endArray1 = "23:59:59".split(":");
			int endHH1 = Integer.valueOf(endArray1[0]);
			int endMinute1 = endHH1 * 60 + Integer.valueOf(endArray1[1]);

			passedTime = endMinute1 - startMinute
					+ getCurrentMinute("HH:mm:ss");
		}

		return passedTime;
	}

	/**
	 * 判断是否是临界天,如果是返回ture
	 * 
	 * @param startTime
	 *            节目播出开始时间
	 * @param endTime
	 *            节目播出结束时间
	 * @return
	 * @throws ParseException
	 */
	private static boolean isCriticalDay(String startTime, String endTime) {
		boolean isCritical = false;
		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");

		try {
			long startTimeLong = df.parse(startTime).getTime();
			long endTimeLong = df.parse(endTime).getTime();
			if (startTimeLong > endTimeLong) {
				isCritical = true;
			} else {
				isCritical = false;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return isCritical;
	}

	/**
	 * 获取网络时间，单位为分钟
	 * 
	 * @return
	 */
	public static int getNetCurrentTime() {
		int currentMinute = 0;
		try {
			URL url;
			url = new URL("http://www.bjtime.cn");
			URLConnection uc;
			uc = url.openConnection();
			uc.connect(); // 发出连接
			long ld = uc.getDate(); // 取得网站日期时间
			Date date = new Date(ld); // 转换为标准时间对象
			currentMinute = date.getHours() * 60 + date.getMinutes();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return currentMinute;
	}

	/**
	 * 得到当前的时间，单位是分钟
	 * 
	 * @param context
	 * 
	 * @return
	 * @throws ParseException
	 */
	public static int getCurrentMinute(String format) {
		// 得到当前系统时间，并转换成long类型
		String currentTime = localZone2G8(format,
				new SimpleDateFormat(format).format(new Date()));
		String[] currentArray = currentTime.split(":");
		int currentHH = Integer.valueOf(currentArray[0]);
		int currentMinute = currentHH * 60 + Integer.valueOf(currentArray[1]);
		return currentMinute;
	}

	/**
	 * 将当地(系统)时间转换成东8区时间
	 * 
	 * @param df
	 * @param currentTime
	 * @return
	 * @throws ParseException
	 */
	public static String localZone2G8(String format, String currentTime) {
		int diffTime = TimeZone.getDefault().getRawOffset()
				- TimeZone.getTimeZone(Constant.TIME_ZONE).getRawOffset();
		if (diffTime != 0) {
			SimpleDateFormat df = new SimpleDateFormat(format);
			long newStime;
			try {
				newStime = df.parse(currentTime).getTime() - diffTime;
				currentTime = df.format(new Date(newStime));
			} catch (ParseException e) {
			}
		}
		return currentTime;
	}

	/**
	 * 将传来的时间转换成当地（系统）时间
	 * 
	 * @param format
	 * @param time
	 * @return
	 * @throws ParseException
	 */
	public static String change2LocalZone(String format, String time) {
		// 默认（服务器）时区-系统的时区
		int diffTime = TimeZone.getTimeZone(Constant.TIME_ZONE).getRawOffset()
				- TimeZone.getDefault().getRawOffset();
		if (diffTime != 0) {
			SimpleDateFormat dfSS = new SimpleDateFormat(format);
			try {
				long newStime = dfSS.parse(time).getTime() - diffTime;
				time = dfSS.format(new Date(newStime));
			} catch (ParseException e) {
			}
		}
		return time;
	}

	/**
	 * 过滤当前时间以下的节目
	 * 
	 * @param programs
	 * @return
	 */
	public static ArrayList<ProgramDetail> filterByTime(
			ArrayList<ProgramDetail> programs) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
		String currentTime = TimeUtil.localZone2G8("yyyy-MM-dd-HH:mm:ss",
				new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss").format(new Date()));
		ArrayList<ProgramDetail> programsTemp = new ArrayList<ProgramDetail>();

		for (int i = 0; i < programs.size(); i++) {
			// <date>2013-05-06</date>+<pftime>1:20:00</pftime>
			ProgramDetail program = programs.get(i);
			String finshProgram = program.getDate().trim() + "-"
					+ program.getPftime().trim();
			try {
				if (df.parse(currentTime).getTime() < df.parse(finshProgram)
						.getTime()) {
					String pstime = change2LocalZone("HH:mm:ss",
							program.getPstime());
					program.setPstime(pstime);
					programsTemp.add(program);
				}
			} catch (ParseException e) {
			}
		}
		return programsTemp;
	}
}
